package com.yww.datastructure.queue;

import java.util.Iterator;

/**
 * @author yww
 * @description 单向环形链表实现的队列
 * @since 2024/2/4 13:33
 */
public class LinkedListQueue<E> implements Queue<E> {
    // 头，哨兵节点
    private final Node<E> head;
    // 尾，最后一个节点
    private Node<E> tail;
    // 元素个数
    private int size;
    // 队列容量
    private final int capacity;

    {
        head = new Node<>(null, null);
        tail = head;
        tail.next = head;
    }


    public LinkedListQueue() {
        this(Integer.MAX_VALUE);
    }

    public LinkedListQueue(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public boolean offer(E value) {
        // 队列已满
        if (isFull()) {
            return false;
        }
        // 新节点必须指向head，形成环
        Node<E> newNode = new Node<>(value, head);
        tail.next = newNode;
        tail = newNode;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        Node<E> first = head.next;
        head.next = first.next;
        // 如果删除的节点是尾，让尾指针指向头哨兵
        if (first == tail) {
            tail = head;
        }
        size--;
        return first.val;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        Node<E> first = head.next;
        return first.val;
    }

    @Override
    public boolean isEmpty() {
        return size == 0 && head == tail;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;

            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E val = p.val;
                p = p.next;
                return val;
            }
        };
    }

    /**
     * 链队节点
     */
    private static class Node<E> {
        E val;
        Node<E> next;

        public Node(E val, Node<E> next) {
            this.next = next;
            this.val = val;
        }
    }
}
